注册 登录
编程论坛 C++教室

[求助] 类模板用法---(当返回值是结构体变量---)

lenghaijun 发布于 2010-11-06 15:51, 1268 次点击
初学啊,从没写过类似代码,在vs上面敲了下,出现以下错误:

1>d:\program and design\visual studio\mfc\learningc\learningc\test.h(45): error C2143: syntax error : missing ';' before '*'
1>d:\program and design\visual studio\mfc\learningc\learningc\test.h(45): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>d:\program and design\visual studio\mfc\learningc\learningc\test.h(45): error C2065: 'Type' : undeclared identifier
源程序是

// test.h
#ifndef TEST_H_H
#define TEST_H_H


template <class Type>
class test
{
public:
    struct point
    {
        Type x;
        Type y;
    };
private:
    point *pointType;

public:

    test(Type a, Type b);

    ~test();

    point* pointer();


};


template <class Type>
test<Type>::test(Type a, Type b)
{
    pointType = new point;
    pointType->x = a;
    pointType->y = b;

}

template <class Type>
test<Type>::~test()
{
    delete pointType;
}

template <class Type>
point *test<Type>::pointer()
{
    return pointType;

}
#endif

// main.cpp

#include "test.h"
#include<iostream>
using namespace std;
void main()
{
    test<int> leng(2,3);
    //cout << leng.pointer();

}

// test.cpp 空
4 回复
#2
lenghaijun2010-11-07 18:24
怎么没人回了~~~

#3
lintaoyn2010-11-08 07:46
template <class Type>
test<Type>::point *test<Type>::pointer()
{
    return pointType;
}
#4
lenghaijun2010-11-09 21:31
回复 2楼 lenghaijun
额 ,貌似还是不行啊

ps: 编译环境为 vs2010
#5
zhoufeng19882010-11-10 09:54
point是一个内部结构,而且这个内部结构是通过模板类型Type来生成的。之前都没试过这么做,做好的是推荐
使用类模板来定义一个point类。这样也会省去很多不必要的麻烦。下面是是修改了你的代码,在VS2008编译通
过:
-------------------------------------------------------------------------------------------------
程序代码:
// test.h
#ifndef TEST_H_H
#define TEST_H_H

template< class Type>
class point
{
public:
    Type x;
    Type y;
};

template <class Type>
class test
{
private:
    point<Type> *pointType;

public:

    test(Type a, Type b);

    ~test();

    point<Type>* pointer();


};

template <class Type>
test<Type>::test(Type a, Type b)
{
    pointType = new point<Type>;
    pointType->x = a;
    pointType->y = b;

}

template <class Type>
test<Type>::~test()
{
    delete pointType;
}

template <class Type>
::point<Type> *test<Type>::pointer()
{
    return pointType;

}
#endif

// main.cpp
#include<iostream>
using namespace std;
void main()
{
    test<int> leng(2,3);
    cout << leng.pointer();
}
// test.cpp 空
你试试这样行不行。
1