-3

我有一个 B 类,它有一个 C 类成员。B 个对象存储在一个向量中。完整代码和输出如下:

#ifndef B_H
#define B_H

#include "C.h"

class B
{
public:
    B( int = 0 );           // constructor
    B( const B& );  // copy constructor
    ~B();           // destructor
    const B &operator=( const B & );    // assignment operator
    C c();          // return C object
    void val( int );// set val
    int val() const;// return val
private:
    C _c;           // C object
    int _val;       // a value
};

#include "B.h"
#include <iostream>

using namespace std;

B::B( int val )
{
    _val = val;

    cout << "B constructor called" << endl;
}

B::B( const B &other )
{
    _c = other._c;

    cout << "B copy constructor called" << endl;
}

B::~B()
{
    cout << "B destructor called" << endl;
}

const B &B::operator=( const B &other )
{
    if ( &other != this ) {     // avoid self-assignment

        _c = other._c;
    }

    return *this;
}

C B::c()
{
    return _c;
}

void B::val( int val )
{
    _val = val;
}

int B::val() const
{
    return _val;
}

#ifndef C_H
#define C_H

class C
{
public:
    C();            // constructor
    ~C();           // destructor
    void val( int );// set val
    int val() const;// return val
private:
    int _val;       // a value
};

#endif

#include "C.h"
#include <iostream>

using namespace std;

C::C()
{
    _val = 0;

    cout << "C constructor called" << endl;
}

C::~C()
{
    cout << "C destructor called" << endl;
}

void C::val( int val )
{
    _val = val;
}

int C::val() const
{
    return _val;
}

#include <vector>
#include <iostream>
#include "B.h"

using namespace std;

const int n = 5;

vector<B> v( n );

int main()
{
    for ( int i = 0; i < n; i++ )
        v[i] = B( i );

    for ( int i = 0; i < n; i++ )
        B &b = v[i];


    for ( int i = 0; i < n; i++ ) {

        B &b = v[i];

        b.c().val( 5 );
    }

    for ( int i = 0; i < n; i++ ) {

        B &b = v[i];

        cout << b.c().val() << endl;
    }

    cin.ignore( 1 );

    return 0;
}

output:

C destructor called
C destructor called
C destructor called
C destructor called
C destructor called
0
C destructor called
0
C destructor called
0
C destructor called
0
C destructor called
0
C destructor called

问题:在每个周期 C 对象被破坏,并且 bc().val() 返回默认值(零)值。

问题:为什么?

输出属于最后两个。

4

2 回答 2

2

您的B::c成员函数C按值返回。也就是说,它将_c对象所持有的B对象从函数中复制出来。您正在调用val该副本并且不影响该成员_c

考虑这一行:

b.c().val( 5 );

b.c()b返回'_c​​ 对象的临时副本。然后你调用val那个临时的。然后临时在语句结束时被销毁。在每次迭代中被破坏的正是这个临时的。那个临时正在输出C destructor called

如果你想影响成员_c,你需要通过引用返回它:

C& B::c()
{
    return _c;
}
于 2013-02-06T14:52:57.927 回答
0

你的问题出在这里:

C c();          // return C object

B对象中。试着理解这是在做什么。

于 2013-02-06T14:52:31.487 回答