2

我的母语是 C#,所以当我开始使用 C++ 时,我想为 C# 中可用的库使用者创建 get/set 糖语法。

所以我写...

template<typename T>
class GetProperty
{
    private:
        T (*get)();
    public:
        GetProperty(T (*get)())
        {
            this->get = get;
        }
        operator T()
        {
            return get();
        }
        template<typename S, typename T>
        GetProperty<S> operator=(GetProperty<T> fool)
        {
            throw 0;
        }
 };

然后,为了使用它,我编写了代码:

template<typename T>
class Vector
{
    private:
        struct LinkItem
        {
            public:
                T* Item;
                LinkItem* Next;
                                GetProperty<int> Length (&getLength);
                LinkItem(T* Item = NULL, int length = 1, LinkItem* Next = NULL)
                {
                    this->Item = Item;
                    this->length = length;
                    this->Next = Next;
                }
                LinkItem& operator =(LinkItem rhs)
                {
                    this->Item = rhs.Item;
                    this->length = rhs.length;
                    this->Next = rhs.Next;
                    return *this;
                }
            private:
                 int length;
                 int getLength()
                 {
                     return length;
                 }
        };
        LinkItem* current;
    .
    .
    .
};

但是,Netbeans 上的 C/C++ 添加(我相信这是 g++ 编译器)声称我正在实例化没有类型的 GetProperty。
根据谷歌搜索,如果有人忘记了 using 语句或包含标题等,就会发生这种情况。
但 int 是一个原语,所以这不可能。
这是怎么回事?

4

2 回答 2

1

您正在构造 GetProperty 对象,同时在结构中声明它。这在 C++ 中是不允许的。您必须将构造移至构造函数。

于 2012-05-25T16:01:34.923 回答
0

除了 VC++ 没有实现非静态数据成员初始化器这一事实之外,您不能将成员函数 getLength 视为int (*)(). 它的类型是int (LinkItem::*)().

struct Foo {
    int foo(void) {return 1;}
};

int main() {
    int (*var)() = &Foo::foo; // Error
    int (Foo::*var)() = &Foo::foo; // Okay
}

您可能不应该尝试像这样导入外国成语,但如果您真的想要,您可以尝试以下操作。(尽管正如 Nicol Bolas 指出的那样,您也可能不应该实现自己的链表,或者将其命名为“向量”。如果您正在学习 C++,只需学习 C++ 的方式,然后再去尝试重新发明事物。)

#include <functional>

template<typename T>
class GetProperty
{
private:
    std::function<int()> get;
public:
    GetProperty(std::function<int()> get)
        : get(get)
    {}
    operator T()
    {
        return get();
    }
};

template<typename T>
class Vector
{
private:
    struct LinkItem
    {
    public:
        T* Item;
        LinkItem* Next;
        GetProperty<int> Length;
        LinkItem(T* Item = NULL, int length = 1, LinkItem* Next = NULL)
            : Length([this] { return this->getLength(); })
        {
...
于 2012-05-25T17:11:12.410 回答