English 中文(简体)
如何利用回收方法获取有活力的物体财产?
原标题:How to access a dynamic object property not using getter method?
  • 时间:2012-01-15 18:41:10
  •  标签:
  • c++
#include <iostream>

class SomeClass
{
 public: int *SomeNumber;

 SomeClass() { SomeNumber = new int; *SomeNumber = 5; }

 ~SomeClass() { delete SomeNumber; }
 int getSomeNumber(void) { return *SomeNumber; }

};

int main()
{

SomeClass A;
std:: cout << A.getSomeNumber() << std::endl; // outputs 5
std:: cout << A.SomeNumber << std::endl; // outputs SomeNumber address

return 0;
}

我如何不使用这种方法获得SomeNumber(SomeNumber)而不是地址? 如果一些Number不是墨水的点子,我可以带A.SomeNumber。

Sorry If I were not clear enough. Thanks in advance.

最佳回答

简单:

*A.SomeNumber

由于<代码>,高于*,因此其行文与代码相同。

*(A.SomeNumber)
问题回答

你可以这样做:

std:: cout << (*A.SomeNumber) << std::endl;

避免使你们的财产公开!

你们可以使用访客设计模式,而不是像这样的守则:

class SomeClass
{
 public: int *SomeNumber;

 SomeClass() { SomeNumber = new int; *SomeNumber = 5; }

 void visit( IVisitor* visitor ){ visitor->doSomething(*SomeNumber);}

 ~SomeClass() { delete SomeNumber; }
 int getSomeNumber(void) { return *SomeNumber; }

};

IVisitor is an interface you can implement it and anything you want.





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签