0

クラスの1つのポインターデータメンバーのコピーコンストラクターを作成しました

class person
{
public:

 string name;
int number;
};



  class MyClass {
     int x;
    char c;
    std::string s;
    person student;
    MyClass::MyClass( const MyClass& other ) :
    x( other.x ), c( other.c ), s( other.s ),student(other.student){}
 };

しかし、このプログラムを実行すると、次のエラーが発生します

エラー:追加の修飾'MyClass ::' onmember'MyClass'[-fpermissive]コピーコンストラクターを適切に使用していますか。

4

3 に答える 3

2
MyClass::MyClass( const MyClass& other )
^^^^^^^^^^

完全修飾名は、クラス定義の外部で本体を定義する場合にのみ必要です。これは、この特定の関数(この場合はコンストラクター)が名前修飾クラスに属していることをコンパイラーに通知します。
クラス定義内で本体を定義する場合、関数はそれを定義しているクラスのメンバーであることが暗示されるため、完全修飾名は必要ありません。

于 2013-02-20T06:45:52.950 に答える
0

浅いコピーが必要な場合(すべてのMyClassインスタンスがの同じコピーを指しているstudent)、次のようにします。

MyClass::MyClass( const MyClass& other ) :
    x( other.x ), c( other.c ), s( other.s ), student( other.student ) {}

それ以外の場合は、次のように実装されるディープコピーが必要です(参照解除に注意してください)。

MyClass::MyClass( const MyClass& other ) :
    x( other.x ), c( other.c ), s( other.s ) {
    student = new person(*(other.student)); // de-reference is required
}

次のコードを実行して、違いを確認します。

MyClass a;
person mike;
mike.name = "Mike Ross";
mike.number = 26;
a.student = &mike;
MyClass b(a);
b.student->number = 52;
cout << a.student->number << endl;
cout << b.student->number << endl;

浅いコピー出力:

52
52

ディープコピー出力:

26
52
于 2013-02-20T10:39:22.327 に答える
0
class person
{
public:

string name;
int number;
};

 class MyClass {
 int x;
 char c;
 std::string s;
 person *student;
 MyClass(const MyClass& other);
};

MyClass::MyClass( const MyClass& other ) :
 x( other.x ), c( other.c ), s( other.s ),student(other.student){
  x = other.x;
  c = other.c;
  s = other.s;
  student = other.student;
 }

これで正常にコンパイルされます。それでも、明示的なコピーコンストラクタと代入演算を適切に実行しているのではないかという疑問が1つあります。

于 2013-02-20T06:58:33.913 に答える