简体   繁体   English

Base成员的重载下标运算符

[英]Overload subscript operator for base's member

#include <iostream>
#include <string.h> // strlen, strcpy

Here we have the Base class with a non-default ctor, a getter for name and its destructor. 在这里,我们有一个带有非默认ctor的Base类,一个用于名称的getter及其析构函数。

class Base {
  char *name_;
public:
  Base(const char* str)
    : name_{new char[strlen(str)]}
  {
    strcpy(name_,str);
  }
  char * name() const
  {
    return name_;
  }
  virtual ~Base()
  {
    delete [] name_;
  }
};

Derived class inherits from Base publicly and has its own non-default ctor. 派生类公开继承自Base,并且具有自己的非默认ctor。

class Derived : public Base {
public:
  Derived(const char* str)
    : Base(str){}
};

My question is how do I make the last line of code in main to work? 我的问题是如何使main中的最后一行代码起作用?

int main()
{
  char d1name[] {"d1"};
  Derived d1(d1name);
  std::cout << d1.name() << std::endl;

  d1.name[0] = 'D';
}

My question is how do I make the last line of code in main to work? 我的问题是如何使main中的最后一行代码起作用?

Just add parenthesis to call the getter 只需添加括号即可调用getter

    d1.name()[0] = 'D';
        // ^^

But in general that's a not so good idea. 但是总的来说,这不是一个好主意。 You could make the char array in your base class public then, or even better use a std::string at all. 然后,您可以将基类中的char数组public ,甚至更好地使用std::string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM