我知道我刚刚问了一个关于此的问题,但我无法弄清楚我做错了什么。我只重写了一小部分,找不到任何错误(在父返回子中使用 C++ 函数作为参考)
我的代码:
#include <iostream>
#include <stdlib.h>
#include <cstring>
using namespace std;
template<class Derived>
class Entity {
private:
string _name;
public:
const string& name() const;
Derived& name( const string& );
Derived* This() { return static_cast<Derived*>(this); }
};
class Client : Entity<Client> {
private:
long int _range;
public:
const long int& range() const;
Client& range( const long int& );
};
const string& Entity::name() const {
return _name;
}
Derived& Entity::name(const string& name) {
_name = name;
return *This();
}
const long int& Client::range() const {
return _range;
}
Client& Client::range( const long int& range ) {
_range = range;
return *this;
}
int main() {
Client ().name("Buck").range(50);
return 0;
}
结果:
untitled:25: error: ‘template<class Derived> class Entity’ used without template parameters
untitled:25: error: non-member function ‘const std::string& name()’ cannot have cv-qualifier
untitled: In function ‘const std::string& name()’:
untitled:26: error: ‘_name’ was not declared in this scope
untitled: At global scope:
untitled:29: error: expected constructor, destructor, or type conversion before ‘&’ token
untitled: In function ‘int main()’:
untitled:13: error: ‘Derived& Entity<Derived>::name(const std::string&) [with Derived = Client]’ is inaccessible
untitled:44: error: within this context
untitled:44: error: ‘Entity<Client>’ is not an accessible base of ‘Client’
我将非常感谢您的回答(我的无能可能是由于睡眠不足:D)