【问题标题】:Structures for dummies假人结构
【发布时间】:2015-01-15 17:45:26
【问题描述】:

我正在研究 C++ 中的结构...我了解它的基本概念,据我所知,它旨在以更紧凑的方式列出一系列项目....但是我遇到了一个示例我不明白发生了什么:

struct cuComplex {
    float   r; // real part of a complex number
    float   i; // imaginary part of a complex number
    /* !!! I DON'T UNDERSTAND FROM HERE !!! */
    cuComplex( float a, float b ) : r(a), i(b)  {}
    float magnitude2( void ) { return r * r + i * i; }
    cuComplex operator*(const cuComplex& a) {
        return cuComplex(r*a.r - i*a.i, i*a.r + r*a.i);
    }
    cuComplex operator+(const cuComplex& a) {
        return cuComplex(r+a.r, i+a.i);
    }
    /* !!! TO HERE. !!! */
};

在我看来,内部定义了某种函数,但我不明白这是怎么可能的以及我应该如何解释它。

问。是否有一些参考资料可供我阅读,以便更好地了解正在发生的事情?

【问题讨论】:

  • 您可以为struct 定义函数,就像class 可以具有函数一样。他们正在定义 1) 构造函数 2) magnitude2 函数 3) * 乘法运算符 4) + 加法运算符
  • 你至少应该知道你正在学习什么语言,并且还要注意 C != C++。很多时候,一个“自然”的答案会与另一个大不相同(甚至可能无法编译)。
  • 请不要编辑掉这是作为 C 问题提出的事实?整个问题在于他试图在 C 编译器中编译 C++ 代码。
  • 代码实际上是 cuda "C" 研究案例的一部分......因为我不是程序员,而且我才刚开始,我相信区分 c 和 c++ 的困难是合理的
  • @FedericoGentile 对不起所有的仇恨者,如果你能坚持下去,这里有很多乐于助人的人。 +1 鼓励你。 meta.stackoverflow.com/questions/266370/…

标签: c++ methods struct constructor operator-overloading


【解决方案1】:

C++ 中的结构与类基本相同,但有一个区别。在类中默认访问说明符是私有的,而在结构中它是公共的。

所以您在该代码中看到的是:-

构造函数、重载运算符 +,* 为您提供结构和计算复数大小的方法。

【讨论】:

    【解决方案2】:

    这就像一个classwith the exception of default member protection,它有成员变量ri,阅读这里了解更多信息:http://www.cplusplus.com/doc/tutorial/classes/

    struct cuComplex {
        float   r;
        float   i; // imaginary part of a complex number
    

    这是一个构造函数,请阅读此处了解更多信息:http://www.cplusplus.com/doc/tutorial/classes/#constructors

        cuComplex( float a, float b ) : r(a), i(b)  {}
    

    这是一个方法或成员函数,如果您已经完成了第一个,就像您已经阅读过的那样,但是如果您想要一个更简洁的示例,请阅读此处:http://en.wikipedia.org/wiki/C%2B%2B_classes#Member_functions

        float magnitude2( void ) { return r * r + i * i; }
    

    这些已超载operators 阅读此处了解更多信息:http://www.cplusplus.com/doc/tutorial/templates/#overloading_operators

        cuComplex operator*(const cuComplex& a) {
            return cuComplex(r*a.r - i*a.i, i*a.r + r*a.i);
        }
        cuComplex operator+(const cuComplex& a) {
            return cuComplex(r+a.r, i+a.i);
        }
    };
    

    如果您有除此之外的具体问题,您可以在这篇文章中发表评论,我会尽力帮助解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-10
      • 2021-07-23
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多