我不太明白为什么对于赋值,派生类不会调用基类的相应运算符,如果它自己不存在的话.看看代码:
#include <iostream>
using namespace std;
class A{
protected:
void myWrite(){
cout << " Base " <<endl;
}
public:
double x,y;
A(): x{0},y{0}{};
virtual A & operator=(double g){x=g;y=g;return *this;}
virtual ~A(){};
virtual void doneit(){myWrite();}
};
class B: public A{
protected:
public:
B():A(){};
virtual ~B(){};
virtual void doneit(){myWrite();}
};
int main() {
A jj;
B pp;
pp=0.0;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
因为它是代码不编译.当然,如果我为B定义一个"运算符="与A的相同,那么一切正常,但是为什么默认情况下不调用B"operator ="如果未定义派生类中的那个?你能帮忙解释一下这个问题吗?
gcc编译器说../src/tito.cpp:40:4:错误:没有可行的重载'='pp = 0.0; ~~ ^ ~~~ ../src/tito.cpp:28:7:注意:候选函数(隐式复制赋值运算符)不可行:对于第一个参数类B,没有已知的从'double'到'const B'的转换:public A {^ 1错误生成.
你能解释一下为什么它不起作用吗?
我有以下模板代码:
class ClassName{};
template <class T>
class TemplatePtr
{
public:
void operator=(T* p)
{
}
};
class TemplatePtr_ClassName: public TemplateePtr<ClassName>
{
public:
~TempaltePtr_ClassName();
};
void Test()
{
TemplatePtr_ClassName data;
data = new ClassName;
}
Run Code Online (Sandbox Code Playgroud)
但编译失败并显示错误消息(VS2008):
错误C2679:二进制"=":没有操作员发现它采用类型>>"类名*"的右边的操作数(或没有可接受的转化率)
为什么它不起作用,因为我在模板基类中定义了一个运算符?
为什么这段代码:
class X {
public:
X& operator=(int p) {
return *this;
}
X& operator+(int p) {
return *this;
}
};
class Y : public X { };
int main() {
X x;
Y y;
x + 2;
y + 3;
x = 2;
y = 3;
}
Run Code Online (Sandbox Code Playgroud)
给出错误:
prog.cpp: In function ‘int main()’:
prog.cpp:14:9: error: no match for ‘operator=’ in ‘y = 3’
prog.cpp:14:9: note: candidates are:
prog.cpp:8:7: note: Y& Y::operator=(const Y&)
prog.cpp:8:7: note: no known conversion for argument 1 …Run Code Online (Sandbox Code Playgroud)