c++ - c++类中方法的实现

标签 c++ class oop

我是 oop 的新手,不知道如何在全局范围内指定此问题。我有两个类(class)。客户端

class Client
{
private:
    int code;
    string name;
public:
    Client(int c, string n);
    int getCode();
    string getName();
};

Client::Client(int c, string n)
{
    this->code = c;
    this->name = n;
}

int Client::getCode()
{
    return this->code;
}

string Client::getName()
{
    return this->name;
}

和帐户

class Account
{
private:
    int number;
    double balance;
    double interestRate;
    Client* owner;
  };

我有这样的方法:

Client* Account::getOwner()
{
    return this->something;
}

你能告诉我,我怎样才能从这个方法中得到客户的代码和名字?

最佳答案

Can you please tell me, how can I get client's code and name from this method?

该方法称为 getOwner。一个名为 getOwner 的方法应该……得到……所有者。没有别的。

如果你想得到所有者的名字,要么写一个新方法

string getOwnerName() const { return owner->getName(); }

或者...

(更好,因为它减少了 Account 和 Client 类之间的耦合,可能更糟,因为它依赖于直接公开所有者,但是你已经在这样做了......)

...只需将此委托(delegate)给客户端代码:

cout << account->getOwner()->getName();

关于c++ - c++类中方法的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49496687/

相关文章:

C++ Boost.serialization 与简单加载/保存

python - 按下随机键时 cv2.waitKey(0) 不等待 - OpenCV 3.1.0、Python3、Ubuntu

c++ - 如何使用来自另一个结构的对象编写成员初始化列表

c++ - C++ 中的类方法等价物

C++ 类声明和命名空间

language-agnostic - "program to an interface"是什么意思?

c++ - 模板类作为参数模板: MSVC error - error C2977: too many template arguments(C++98)

javascript类可访问性变量作用域问题

c++ - 使用 void *pointer to object 的安全性

c++ - 为什么我的编译器将字符串视为 const char[]?