【发布时间】:2016-07-11 19:25:54
【问题描述】:
我正在尝试编写一个类Core,它的成员变量是一个指针。复制构造函数是Core(Core& x) 而不是Core(const Core& x)。
Core有一个成员函数Core Core::new_core (int * ptr),我尝试构造Core new_core= core.new_core(ptr);时代码有问题,请看下面的代码和错误信息。
#include<iostream>
class Core
{
private:
int* a;
public:
Core(int* in) {a=in;}
Core(Core& x) {a = x.data();}
inline const int * data() const {return a;}
inline int * data() {return a;}
Core new_core (int * ptr)
{
Core b(ptr);
return b;
}
};
using namespace std;
int main()
{
int ptr[3]= {1,2,3};
Core core(ptr);
Core new_core= core.new_core(ptr);
cout<< new_core.data() <<endl;
return 0;
}
错误信息:
main.cpp:在函数'int main()'中:
main.cpp:30:37: 错误:没有匹配函数调用‘Core::Core(Core)’
Core new_core= core.new_core(ptr); ^main.cpp:30:37: 注意:候选人是:
main.cpp:12:6: 注意:Core::Core(Core&)
Core(Core& x) { a = x.data() ;} ^main.cpp:12:6: 注意:参数 1 没有从‘Core’到>‘Core&’的已知转换
main.cpp:10:6: 注意:Core::Core(int*)
Core(int* in) {a=in;} ^main.cpp:10:6: 注意:没有已知的参数 1 从“核心”到 'int*'
我可以通过替换轻松解决问题
Core(Core& x) { a = x.data() ;}
到
Core(const Core& x) { a = const_cast<int* > ( x.data() ) ;},
有没有更好的方法来解决这个问题而不使用 const_cast?
我想保持int* a 不公开,并保持以下两行:
inline const int * data() const {return a;}
inline int * data() {return a;}
谢谢。
【问题讨论】:
-
这真的取决于你想让这个类做什么。鉴于它只引用外部数据,
int * data()不是const有意义吗?即int * data() const;. -
谢谢你,juanchopanza。我举了一个太笼统的例子。在我的实际应用程序中,Core 是一个派生类, const int * data() const 来自基类,我无法更改。我想我必须使用 Core(const Core& x) 来解决问题?
-
您的问题是非常量右值引用不能绑定到临时值。但是右值引用可以。有一个答案(现已删除)几乎是正确的......
-
顺便说一句,如果我使用:
Core core_a(ptr);Core core_b( core_a);,代码可以正常工作。为什么我不能使用Core new_core( core.new_core(ptr) );? -
我明白了,非常感谢。
标签: c++ pointers constructor constants