一开始的程序里 类不能连续赋值,内存会报错。debug了一整晚发现是new里面的数组n++出错。经过测试++n和n+1都能使程序正确运行。
n++会报错是因为先使用n,再对n加1。而我们的期望是开辟一个n+1长度的数组而不是n,所以会报错。
在单语句中,自增运算和普通的加法没有区别,但是在这种复合语句中千万小心,尽量不使用n++和++n
#pragma once #ifndef COW_H_ #define COW_H_ class Cow { private: //class default private,struct default public char name[20]; char * hobby; double weight; public: Cow(); Cow(const char * nm, const char * ho, double wt); Cow(const Cow & c); ~Cow(); Cow & operator=( const Cow & c); void ShowCow() const; //display all cow data }; #endif // !COW_H_
cow.h
#include"Cow.h" #include<cstring> #include<iostream> using std::strcpy; Cow::Cow() { name[0] = ‘\0‘; hobby = new char[1];//为了统一构造函数的型式,兼容析构函数 hobby[0] = ‘\0‘; weight = 0; } Cow::Cow(const char * nm, const char * ho, double wt) { weight = wt; strcpy(name, nm); int n; n = strlen(ho); hobby = new char[n+1];//记得加1 strcpy(hobby, ho); } Cow::Cow(const Cow & c) { weight = c.weight; strcpy(name, c.name); int n; n = strlen(c.hobby); hobby = new char[n+1]; strcpy(hobby, c.hobby); } Cow::~Cow() { delete[]hobby; hobby = nullptr; } void Cow::ShowCow() const { using std::cout; using std::endl; cout << name << endl; cout << hobby << endl; cout << weight << endl; } Cow & Cow::operator=(const Cow & c)//记得要return { //先删除后创建,节约内存 if (this == &c)//判断万一是自身 { return *this; } delete[] hobby; strcpy(name, c.name); int n; n = strlen(c.hobby); hobby = new char[n+1]; strcpy(hobby, c.hobby); weight = c.weight; return *this; } //连续赋值出错原因竟然是++n!! //千万不要在new里面n++,尽量少用自增 //++n和n+1都可以,但是n++不行,因为new是先new了n,n再加1,当n++自增运算不是但语句时候,不要用,容易出错,就像这种在括号里的型式
cow.cpp
#include <iostream> #include <cstring> #include"Cow.h" using std::strcpy; using std::cin; using std::cout; using std::endl; int main() { Cow milk("a", "eat", 56.9);//Cow::Cow ( const char *nm, const char *ho, double wt ) Cow junk("t", "c", 200.66);//Cow::Cow ( const char *nm, const char *ho, double wt ) milk.ShowCow(); cout << endl; Cow m1;//Cow::Cow() m1 = milk;//Cow & Cow::operator= ( const Cow & c ) m1.ShowCow(); cout << endl; Cow m2 = junk;//Cow::Cow ( const Cow & c ),等价于m2(junk) m2.ShowCow(); cout << endl; Cow m3;//Cow::Cow() m3.ShowCow(); cout << endl; m3 = m1 = m2;//Cow & Cow::operator= ( const Cow & c ) //m3 = m1; //m3.ShowCow(); //m3 = m2; m3.ShowCow(); //为什么两次赋值会出错? cout << "ok" << endl; return 0; }
test.cpp
原文地址:https://www.cnblogs.com/syne-cllf/p/9252136.html
时间: 2024-10-09 07:16:03