1

到目前为止,我已经阅读了带有和不带有指针的结构。我的问题是关于结构与类和主要的结合。我从 K&R 和 c++ 站点学到的是结构不能包含值。我要分配给成员的值将是常量。在几篇文章中,我读到我应该将结构放在类中,甚至放在私有中。我使用的设置是:

class C
{
struct something {const float m = 3} s;` //actually 12 members. Compiler doesn't accept  values: "ISO C++ forbids initialization of member"

function foo(struct something s){ float m = s.m; <..do something..>}` //struct s actually used in several functions

};    

int main(){C c;}

然后我创建了 2 个结构,并让第二个将值分配给第一个的成员,我觉得这很难看。但是为什么这会被 gcc 接受呢?那么我怎样才能以正确的方式只分配一次值,因为分配值必须在函数内部完成。顺便说一句,我使用的是 Ubuntu gcc-4.6.1。

谢谢你的回答。

4

3 回答 3

1

structclassC++之间的区别在于, structs 默认其成员为,public而类默认为private(继承也是如此)。这里的所有都是它的。

然后,在 C++03const float m = 3;中作为成员声明无效。您需要为您的结构声明一个构造函数:

struct something
{
    const float m;
    const float n;
    something() : m(3), n(42) {}
} s;
于 2013-10-23T08:36:41.377 回答
1
struct something {const float m = 3} s;` //actually 12 members. Compiler doesn't accept  values: "ISO C++ forbids initialization of member"

to fix above do

struct something {
    something (float const& f = 3) : m(f)
    const float m;
} s;
于 2013-10-23T08:38:16.867 回答
0

Structs AND classes in C++ suffer from this problem. You can only declare a value in a class definition if the variable is static and shared among all the instances of the class. If your variable is const I think that may be a good choice.

A good solution for non-const variables is a simple one - assign the desired values to all the variables in the default constructor of your class or struct.

e.g

struct Something
{
  float value;

  Something():value(5.0f) {};

}
于 2013-10-23T08:39:18.380 回答