我还在学习类,复制构造函数和重载运算符,所以任何建议/帮助/ - > s都很受欢迎!!!
我正在尝试使用类Test2创建一个复制构造函数,该类具有来自另一个类Test1的私有成员变量。我在代码中评论了给我业务的复制构造函数。
以下是编译时遇到的错误:
assOp.cpp: In copy constructor 'Test2::Test2(const Test2&)':
assOp.cpp:102:25: error: passing 'const Test2' as 'this' argument of 'int Test2:
:getNum()' discards qualifiers [-fpermissive]
setNum(original.getNum());
^
assOp.cpp:103:27: error: passing 'const Test2' as 'this' argument of 'char* Test
2::getChar()' discards qualifiers [-fpermissive]
setChar(original.getChar());
以下是代码:
#include <iostream>
#include <cstring>
using namespace std;
class Test1
{
public:
Test1();
Test1(const Test1& original);
int getNum();
char *getChar();
void setNum(int x);
void setChar(char y[]);
private:
int num;
char *ch;
};
class Test2
{
public:
Test2();
Test2(const Test2& original);
void setNum(int x);
void setChar(char y[]);
int getNum();
char *getChar();
private:
Test1 foo;
};
int main()
{
Test1 a;
Test2 b;
return 0;
}
Test1::Test1()
{
num = 1234;
ch = new char[5];
strcpy(ch,"test");
}
Test1::Test1(const Test1& original)
{
int length = strlen(original.ch);
num = original.num;
ch = new char[length + 1];
strcpy(ch, original.ch);
ch[length] = '\0';
}
int Test1::getNum()
{
return num;
}
char *Test1::getChar()
{
return ch;
}
void Test1::setNum(int x)
{
num = x;
}
void Test1::setChar(char y[])
{
int length = strlen(y);
ch = new char[length + 1];
strcpy(ch, y);
ch[length] = '\0';
}
Test2::Test2()
{
}
//Sassy copy constructor that thinks its better than me
Test2::Test2(const Test2& original)
{
setNum(original.getNum());
setChar(original.getChar());
}
void Test2::setNum(int x)
{
foo.setNum(x);
}
void Test2::setChar(char y[])
{
foo.setChar(y);
}
int Test2::getNum()
{
return foo.getNum();
}
char *Test2::getChar()
{
return foo.getChar();
}
^
答案 0 :(得分:2)
问题是由
引起的 int getNum();
char *getChar();
由于这些函数不是const
成员函数,因此不能在const
对象上使用它们。作为一般规则,使所有getter函数const
成员函数。
int getNum() const;
char const* getChar() const;