我的参考参数存在以下问题: 当我们有一个带参考参数的函数时,编译器会自动传递给该函数,即调用它的任何参数的地址。 示例(带对象):
class sample {
char *s;
public:
sample(); // normal constructor
sample(const sample &ob); // copy constructor
~sample( ) { if(s) delete [] s; cout << "Freeing s\n"; }
void show() { cout << s << "\n"; }
void set(char *str);
};// Definition will be excluded from here`
我们有一个带有这个类实例的参考参数的函数,
像:
void funtionWithRef(sample &kk); // declaration
void funtionWithRef(sample &sam){ // definition
sam.show();
}
和一个返回对象类型为sample的函数:
sample functionReturnSample(); //declaration
sample functionReturnSample(){ // definition
sample sam;
sam.set("test sample");
return sam;
}
现在,当我们这样做时:
int main() {
sample temp = functionReturnSample();
funtionWithRef(temp);
return 0;
}
它完美无缺。当我们将 temp 对象作为参数添加到 funtionWithRef 时,编译器将该对象的地址传递给该函数。 但为什么它不起作用,如果我们 NOT 首先将 functionReturnSample 的返回值分配给实例,但直接将该方法设置为论点如:
funtionWithRef(functionReturnSample());
为什么这会有所不同,当我们做同样的事情时,根据我咨询过的一些书,请应该
修改
@ user657267 这是完整的例子(源丛书:C ++ From Ground Up,3rd Edition,page 219-320):
class sample {
char *s;
public:
sample(); // normal constructor
sample(const sample &ob); // copy constructor
~sample( ) { cout << "s: " << s <<" ,Freeing s\n"; if(s) delete [] s;}
void show() { cout << s << "\n"; }
void set(char *str);
sample operator=(sample &ob); // overload assignment
};
// Normal constructor.
sample::sample() {
s = new char('\0'); // s points to a null string.
cout << "Normal constructor: s: " << strlen(s) << endl;
}
// Copy constructor.
sample::sample(const sample &ob) {
cout << "Copy constructor: ob.s: "<< ob.s << " ,strlen(ob.s): " << strlen(ob.s) << "\n";
s = new char[strlen(ob.s)+1];
strcpy(s, ob.s);
}
// Load a string.
void sample::set(char *str) {
s = new char[strlen(str)+1];
strcpy(s, str);
}
// Overload assignment operator.
sample sample::operator=(sample &ob) {
/* If the target memory is not large enough
then allocate new memory. */
cout << "operator= strlen(ob.s): " << strlen(ob.s) << " ,strlen(s): " << strlen(s) << endl;
if(strlen(ob.s) > strlen(s)) {
cout << "operator= Larger memory of target object. Deleting current...\n";
delete [] s;
s = new char[strlen(ob.s)+1];
}
strcpy(s, ob.s);
return *this;
}
// Return an object of type sample.
sample input() {
char instr[80];
static sample str;
cout << "Enter a string: ";
cin >> instr;
str.set(instr);
return str;
}
int main() {
sample ob;
// assign returned object to ob
ob=input(); // This is now OK
ob.show();
return 0;
}
这不会编译,并报告错误:
**error: no match for ‘operator=’ (operand types are ‘sample’ and ‘sample’)**
所以它是上述书中代码的复制/过去。你可以查一下。
但是,如果我将overloaded = operator参数指定为 const ,我会想:
sample operator=(const sample &ob); // overload assignment
然后 DOES 工作。 然而,困扰我的是,现在当我有可运行的代码时,我不明白为什么两次次复制构造函数被调用。 我知道当 input()函数返回时调用它,并创建临时对象,但我不知道为什么第二次,因为我知道(但也许我错了)复制构造函数< strong> NOT 调用赋值操作(同一本书,第291-292页),但看起来,尽管如此,当 return * this; 被调用时(重载运算符返回值时) ),复制构造函数被调用? 那是什么呢? Thankx