小编Trv*_*ack的帖子

创建一个从其他类成员自动计算的类成员?

  1. 在编程方面,我是一个绝对的新手,我试图通过解决C++中一些简单的"问题"来自学基础知识.

  2. 我已经在网上搜索了我的问题的确切答案,然后在这里发布并且到目前为止还没找到,但这可能是因为(1).

所以,我正在寻找的是一种声明一个类成员的方法,该类成员可以从同一个类的其他成员自动计算,因此计算出来的类成员可以像显式定义的类成员一样使用.例如,想象一个名为creature的结构,它具有属性/ members creature.numberofhands,creature.fingersperhand,最后是属性creature.totalfingers,它们自动从上面的成员计算出来.

以下是我最接近我想达到的目标的一个例子:

#include <iostream>

typedef struct creature {
    int numberofhands;
    int fingersperhand;
    int totalfingers();
} creature;    

int creature::totalfingers()
{
    return numberofhands * fingersperhand;
};

int main()
{
    creature human;
    human.numberofhands = 2;
    human.fingersperhand = 5;

    printf("%d",human.totalfingers());
    return(0);
}
Run Code Online (Sandbox Code Playgroud)

对此我真烦恼的是,我必须从明确定义的那个中处理计算出的一个,即我必须在它之后加上"()".我怎样才能更改代码,所以我可以使用:human.totalfingers而无需明确定义它?

c++ class

4
推荐指数
1
解决办法
118
查看次数

子类成员变量作为初始化列表中的主类构造函数的参数= crash?

编程非常新,所以请原谅我可能没有看到明显的东西.

基本上我只是想知道为什么所有三个代码都编译,但是在TWO和THREE情况下产生的可执行文件CRASH(我用注释标记了差异)

ONE - 编译

#include <iostream>
#include <string>
using namespace std;

string testrace = "dog"; //defining it only globally

class Attributes {
    public:
    Attributes (string race){
        if (race == "human"){
            intelligence = 10;}
        else if (race == "dog"){
            intelligence = 4;}
    }
    int intelligence;
};

class Dalmatian: public Attributes{
    public:
        // but NOT locally
        Dalmatian (): Attributes{testrace} { //using it as an argument
            cout << "do i even arrive here" << endl;
        }
};

int main() {
    Dalmatian bob; …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance initialization-list

1
推荐指数
1
解决办法
37
查看次数

标签 统计

c++ ×2

class ×1

inheritance ×1

initialization-list ×1